(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.popup.availabilityController', availabilityController);
	availabilityController.$inject = [ '$scope', '$q', '$uibModalInstance', 'Constants', 'dialogsModule', 'gridService', 'modalService', 'layoutConfig', 'validatorConfig', 'authService', 'ajaxServiceFactory' ];
	function availabilityController($scope, $q, $uibModalInstance, Constants, dialogsModule, gridService, modalService, layoutConfig, validatorConfig, authService, ajaxServiceFactory) {
		var ctrl = this, log = $scope.loggerFactory.getLogger("availability"), ajaxService = ajaxServiceFactory.buildAjaxService({
			getLayoutConfigByFacilityId: {
				url : 'do/cda/facility/layout',
				method : 'post'					
			},
			facilityQuery: {
				url : 'do/cda/facility/facilityQuery',
				method : 'post'					
			}
		});
		ctrl.dialogsModule = dialogsModule;
		//ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.facility = {};
		ctrl.facility.facilityAttrList = [];

		ctrl.init = function() {
			ctrl.limitNodeIdOptions = {'data' : []};
			if (ctrl.attribute) {
				for (var i = 0; i < ctrl.attribute.length; i++) {
					var childLimitNode = ctrl.attribute[i];
					var option = {};
					option.value = childLimitNode.id;
					option.label = childLimitNode.label;
					ctrl.limitNodeIdOptions.data.push(option);
				}
			}
			if(dialogsModule.params.facilityId){
				var params = {'facilityId' : dialogsModule.params.facilityId};
				ctrl.facility.facilityId = dialogsModule.params.facilityId;
				ajaxService.getLayoutConfigByFacilityId(params).then(function(response){
					var layoutConfig = response.data;
					ctrl.layoutConfig = layoutConfig;
				});
			}
		};
		
		ctrl.calculate = function () {
			ajaxService.facilityQuery(ctrl.facility).then(function(response){
				angular.merge(ctrl.facility, response.data);
			},function(response){
				modalService.openErrorDialogs({
					'messages' : response.error
				});
			});
		};
		
		ctrl.ok = function() {
			if ($scope.childNodeForm) {
				$scope.childNodeForm.$setSubmitted();
			}
			if ((!$scope.childNodeForm || $scope.childNodeForm.$valid) && (!dialogsModule.btnCallback || !dialogsModule.btnCallback['ok'] || dialogsModule.btnCallback['ok'](ctrl.childNode) !== false)) {
				$uibModalInstance.close();
			}
		};
		
		ctrl.close = function() {
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback['close'] || dialogsModule.btnCallback['close']() !== false) {
				$uibModalInstance.dismiss();
			}
		};
		
	}
})(angular);